package 力扣_树算法.二叉树;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 226. 翻转二叉树
 * @author zx
 * @create 2022-04-13 17:14
 */
public class Num226 {
    /**
     * @return 递归写法二
     */
    public TreeNode invertTree2(TreeNode root) {
        if(root == null){
            return root;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        //需要交换两棵子树的位置
        root.right = left;
        root.left = right;
        return root;
    }
    /**
     * @return 递归写法一
     */
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return root;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    /**
     * 层序遍历方式反转
     */
    public TreeNode invertTree3(TreeNode root) {
        if(root == null){
            return root;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0;i < size;i++){
                TreeNode node = queue.poll();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
        }
        return root;
    }
}
